# *-* coding:utf8 *-*
from flask import render_template, session, current_app, g, abort, request

from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu
from flask import jsonify

@news_blu.route('/<int:news_id>')
@user_login_data
def news_datall(news_id):


    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)

    except Exception as e:
        current_app.logger.error(e)

    click_news_list = list()
    for new in news_list :
        click_news_list.append(new.to_basic_dict())

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        # 返回数据未找到
        abort(404)
    news.clicks += 1


    is_collected = False
    # 判断是否收藏过该新闻
    if g.user:
        if news in g.user.collection_news:
            is_collected = True
        # if news.user.followers.filter(User.id == g.user.id).count() > 0:

            is_followed = True
    # 获取新闻评论
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()

    except Exception as e:
        current_app.logger.error(e)

    comment_like_ids = list()
    if g.user:
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                # 取到用户在当前新闻的所有评论点赞的记录
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                            CommentLike.user_id == g.user.id).all()
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comment_list = []
    for item in comments if comments else []:
        comment_dict = item.to_dict()
        comment_dict["is_like"] = False

        if g.user and item.id in comment_like_ids:
            comment_dict["is_like"] = True

        comment_list.append(comment_dict)
    # 当前登陆的用户是否关注
    is_followed = False

    if news.user and g.user:
        if news.user in g.user.followers:
            is_followed = True

    data = {
        "news":news.to_dict(),
        "click_news_list":click_news_list,
        "is_collected":is_collected,
        "user_info":g.user.to_dict() if g.user else None,
        "comment_list":comment_list,
        'is_followed':is_followed
    }
    # print(data)
    # print(comment_list)  # []
    #  # false
    # print(is_collected)
    return render_template('news/detail.html',data=data)


@news_blu.route('/news_collect',methods = ['POST'])
@user_login_data
def news_collect():
    # 收藏
    user = g.user
    json_tada = request.json
    news_id = json_tada.get('news_id')
    action = json_tada.get('action')

    if not user:
        return jsonify(errno = RET.SESSIONERR,errmsg = '用户未登陆')

    if not news_id:
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    if action not in ("collect","cancel_collect"):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')


    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据库查询错误')

    if not news:
        return jsonify(errno = RET.NODATA,errmsg = '数据不存在')

    if action == "collect":
        user.collection_news.append(news)

    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DATAERR,errmsg = '保存失败')

    return jsonify(errno = RET.OK,errmsg = 'OK')


@news_blu.route('/news_comment',methods = ['POST'])
@user_login_data
def news_comment():
    '''评论'''
    user = g.user

    if not user:
        return jsonify(errno = RET.SESSIONERR,errmsg = '用户未登陆')

    json_data = request.json
    news_id = json_data.get('news_id')
    comment_str = json_data.get('comment')
    parent_id  = json_data.get('parent_id')


    if not all([comment_str,news_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询数据库错误')

    if not news:
        return jsonify(errno = RET.NODATA,errmsg = '新闻数据不存在')

    # 初始化数据模型
    comment = Comment()
    comment.news_id = news_id
    comment.user_id = user.id
    comment.content = comment_str

    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '保存数据失败')

    return jsonify(errno = RET.OK,errmsg = 'OK', data=comment.to_dict())


@news_blu.route('/comment_like',methods = ['POST'])
@user_login_data
def comment_like():
    '''点赞'''
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    data_json = request.json
    comment_id = data_json.get('comment_id')
    action = data_json.get('action')

    if not all([comment_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    if action not in ('add','remove'):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误！！')

    try:
        comment = Comment.query.get(comment_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询数据库失败')
    if not comment:
        jsonify(errno = RET.NODATA,errmsg = '评论数据不存在')

    if action =='add':
        comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                      CommentLike.comment_id == comment.id).first()

        if not comment_like:

            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = g.user.id
            db.session.add(comment_like)
            # 增加点赞数据
            comment.like_count += 1

    else:
        # 删除点赞数据
        comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                      CommentLike.comment_id == comment.id).first()

        if comment_like:
            db.session.delete(comment_like)

            comment.like_count -=1

    try:
        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '操作失败')

    return jsonify(errno = RET.OK,errmsg = 'OK')

@news_blu.route('/followed_user',methods=['POST'])
@user_login_data
def followed_user():

    if not g.user:
        return jsonify(errno = RET.SESSIONERR,errmsg = '用户未登陆')


    # 获取 参数
    json_data = request.json
    user_id = json_data.get('user_id')
    action = json_data.get('action')

    if not all([user_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    if action not in ("follow", "unfollow"):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    # 查询到关注的用户信息
    try:
        order = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "数据库查询错误")

    if not order:
        return jsonify(errno = RET.NODATA,errmsg = '未查询到数据')

    # 根据用户的选择做不同的是
    if action == 'follow':
        if order not in g.user.followed:
            g.user.followed.append(order)

        else:
            return jsonify(errno = RET.DATAERR,errmsg = '当前用户已经被关注')

    else:
        if order not in g.user.followed:
            g.user.followed.remove(order)

        else:
            return jsonify(errno = RET.DATAERR,errmsg = '用户未被关注')

    return jsonify(errno = RET.OK,errmsg = 'OK')


